package service

import (
	"context"
	coreV1 "k8s.io/api/core/v1"
	metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
)

func CreateSecret(clientSet *kubernetes.Clientset, request CreateDockerSecreteRequest) (secretInfo *coreV1.Secret, err error) {

	//a := map[string]map[string]map[string]string{
	//	"auths": {
	//		"10.252.97.57": {
	//			"auth": "YWRtaW46MVcyM2x5YzQ1ag==",
	//		},
	//	},
	//}
	//data, _ := json.Marshal(a)
	data := []byte(request.ConfigJson)
	secretInfo = &coreV1.Secret{
		ObjectMeta: metaV1.ObjectMeta{
			Name: request.SecretName,
		},
		Type: "kubernetes.io/dockerconfigjson",
		Data: map[string][]byte{
			".dockerconfigjson": data,
		},
	}

	secretInfo, err = clientSet.CoreV1().Secrets(request.NamespaceName).Create(context.TODO(), secretInfo, metaV1.CreateOptions{})
	if err != nil {
		return secretInfo, err
	}
	return secretInfo, nil
}

func GetSecretList(clientSet *kubernetes.Clientset, namespaceName string) (secretList *coreV1.SecretList, err error) {
	secretList, err = clientSet.CoreV1().Secrets(namespaceName).List(context.TODO(), metaV1.ListOptions{})
	if err != nil {
		return nil, err
	}
	return secretList, err
}

func GetSecret(clientSet *kubernetes.Clientset, namespaceName string, secretName string) (secretInfo *coreV1.Secret, err error) {
	secretInfo, err = clientSet.CoreV1().Secrets(namespaceName).Get(context.TODO(), secretName, metaV1.GetOptions{})
	if err != nil {
		return nil, err
	}
	return secretInfo, err
}

func ApplySecret(clientSet *kubernetes.Clientset, request ApplySecretRequest) (secretInfo *coreV1.Secret, err error) {

	secretInfo, err = clientSet.CoreV1().Secrets(request.NamespaceName).Get(context.TODO(), request.SecretName, metaV1.GetOptions{})
	if err != nil {
		return nil, err
	}

	data := []byte(request.ConfigJson)
	secretInfo.Data = map[string][]byte{
		".dockerconfigjson": data,
	}

	secretInfo, err = clientSet.CoreV1().Secrets(request.NamespaceName).Update(context.TODO(), secretInfo, metaV1.UpdateOptions{})
	if err != nil {
		return secretInfo, err
	}

	return secretInfo, nil
}

func DeleteSecret(clientSet *kubernetes.Clientset, request DeleteSecretRequest) (err error) {
	err = clientSet.CoreV1().Secrets(request.NamespaceName).Delete(context.TODO(), request.SecretName, metaV1.DeleteOptions{})
	if err != nil {
		return err
	}
	return nil
}
